<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>中间件实现</title>
</head>
<body>
<script type="text/javascript">
    /**
     * 中间件
     */
    function MiddleWare() {
        //中间件缓存
        this.caches = []
        //options选项
        this.options = {}
        // 中间件集合
        this.middlewares = []
    }

    /**
     * 添加（收集）中间件
     * @param { String } pattern:
     * @param { Function } features:
     */
    MiddleWare.prototype.use = function (pattern, features) {
        if (typeof features !== "function") {
            throw Error("middleware must be a function method .")
        }
        this.caches.push({rule: pattern, features: features})
        return this
    }
    /**
     * 执行
     */
    MiddleWare.prototype.execute = function (options) {
        this.middlewares = this.caches.filter(item => item.rule === options)
        console.log("this.middlewares:",this.middlewares)
        this.options = options
        this.next()
    }
    /**
     * 调度执行下一个中间件
     */
    MiddleWare.prototype.next = function () {
        if (this.middlewares.length > 0) {
            const ware = this.middlewares.shift()
            console.log("ware:",ware.features)
            ware.features.call(this, this.options, this.next.bind(this))
        }
    }


    const app = new MiddleWare()
    app.use("/", (req, res, next) => {
        console.log("请求主页")
    })
    app.use("/home", (req, res, next) => {
        console.log("请求首页")
    })
    app.use("/message", (req, res, next) => {
        console.log("请求消息页面")
    })
    app.use("/about", (req, res, next) => {
        console.log("请求关于页面")
    })
    console.log("app:", app)
    app.execute("/home")
    app.execute("/message")
</script>
</body>
</html>
